<?php

namespace App\Trip\Plane\Rules;

use Illuminate\Contracts\Support\Arrayable;
use PHPUnit\Util\Exception;
use Str;

class ParseLuggageVolume implements Arrayable
{


    private string $volume;
    private string $total = '';
    private array  $volumes;
    private string $glue;

    public function __construct(string $volume)
    {
        $this->glue   = '×';
        $this->volume = strtolower($volume);

        if (Str::contains($this->volume, 'x')) {
            $volumes = explode('x', $this->volume);
            if (count($volumes) != 3) {
                throw new Exception("体积格式错误");
            }
            $this->volumes = [
                'length' => $volumes[0],
                'width'  => $volumes[1],
                'height' => $volumes[2],
            ];
        }
        if (Str::contains($this->volume, '×')) {
            $volumes = explode('×', $this->volume);
            if (count($volumes) != 3) {
                throw new Exception("体积格式错误");
            }
            $this->volumes = [
                'length' => $volumes[0],
                'width'  => $volumes[1],
                'height' => $volumes[2],
            ];


        } elseif (Str::contains($this->volume, '*')) {
            $volumes = explode('*', $this->volume);
            if (count($volumes) != 3) {
                throw new Exception("体积格式错误");
            }
            $this->volumes = [
                'length' => $volumes[0],
                'width'  => $volumes[1],
                'height' => $volumes[2],
            ];

        } else {
            $this->volumes = [];
            $this->total   = $this->volume ?: '';
        }
    }

    public function toArray(): array
    {
        $ret = [
            'limit'   => $this->getTotal(),
            'origin'  => $this->volume,
            'desc'    => $this->getDesc(),
            'desc_uy' => $this->getDesc('uy'),
        ];
        return array_merge($ret, $this->getVolumes());
    }

    private function getTotal(): string
    {
        return $this->total;
    }

    private function getDesc($lang = ''): string
    {
        $vs = $this->getVolumes();
        if (!empty($vs)) {
            $desc = "体积不超过";
            if ($lang) {
                $desc = __($desc, [], $lang);
            }

            return "{$desc}{$vs['length']}{$this->glue}{$vs['width']}{$this->glue}{$vs['height']}CM";
        } else if ($this->getTotal()) {
            $desc = "体积不超过三边之和小于（等于）";
            if ($lang) {
                $desc = __($desc, [], $lang);
            }
            return "{$desc}{$this->getTotal()}CM";
        } else {
            return "";
        }
    }

    private function getVolumes(): array
    {
        return $this->volumes;
    }

}